/**
 * 第一步：先引入 axios
 */
import axios from "axios";
import router from "../../router";
/**
 * 第二步：创建 axios 异步请求
 * 包含 请求的url ，请求头返回的格式
 * @type {AxiosInstance}
 */
const service = axios.create({
  baseURL: "/web",
  headers: {
    "content-type": "application/json",
  },
  withCredentials: false,
});
// 处理请求事件
service.interceptors.request.use((config) => {
  console.log(import.meta.env.VITE_APP_BASE_URL);
  if (!localStorage.getItem("phone") && !localStorage.getItem("token")) {
    router.push({ path: "/login" });
  }
  // if (!config.headers["Authorization"]) {
  //   config.headers["Authorization"] = "Bearer " + localStorage.ACCESS_TOKEN;
  // }
  return config;
});
// 处理响应事件
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    const { code, message } = res;
    // HTTP 状态码不为200
    if (code == 200) {
      return Promise.resolve(res);
    }
    // if (code == 500) {
    //   return router.push({ path: "/login" });
    // }
    return Promise.reject(message || "请求错误");
  },
  (error) => {
    const errMsg =
      error.response.data.message || error.response.data.message || "请求失败";
    return Promise.reject(errMsg);
  }
);
export default service;
